<!--
 * @Author: LAB
 * @Date: 2021-05-18 11:40:44
 * @Description: 药品基础信息
 * @FilePath: \HisDrugWeb\client-app\src\views\drug\components\drug-sku.vue
-->
<template>
  <div>
    <CreateDrugStadard
      v-model:value="isCreateDrug"
      :specificationId="editSpecificationId"
      :drugId="drugId"
      :drugSchemeId="drugSchemeId"
      @success="addSuccess"
    ></CreateDrugStadard>
    <CreateDrugStadardzh
      v-model:value="isCreateDrugSkuZc"
      v-model:specificationId="editSpecificationId"
      v-model:drugId="drugId"
      @success="addSuccess"
      :drugSortId="drugSortId"
      :drugSchemeId="drugSchemeId"
    >
    </CreateDrugStadardzh>
    <CreateDrugAgree
      v-model:value="isCreateDrugTaboo"
      @success="addSuccess"
      :drugId="drugId"
      :drugType="drugType"
      :drugSchemeId="drugSchemeId"
      :specificationId="editSpecificationId"
    />
    <CreateDrugMade
      v-model:value="isCreateDrugMade"
      @success="addSuccess"
      :drugId="drugId"
      :drugType="drugType"
      :drugSchemeId="drugSchemeId"
      :specificationId="editSpecificationId"
    />
    <DataGrid
      v-bind="DataGridSetting"
      :data-source="items"
      @context-menu-preparing="setRightMenu"
      :remote-operations="false"
      :selectedRowKeys="selectedRowKeys"
      @selectionChanged="selectItem"
    >
      <!-- @selectionChanged="selectionChanged" -->
      <template #uploadImg="{ data: cellInfo }">
        <imageUpload
          :limit="1"
          :files="cellInfo.Value"
          @change="cellInfo.setValue"
        />
      </template>
      <template #headerTemplate="{ data: column }">
        <div class="header-input" style="width: 100%">
          <div
            style="width: 60%"
            v-if="!isEditHeader[column.columnIndex]"
            @dblclick="isEditHeader[column.columnIndex] = true"
            @click.stop="none"
          >
            {{ getHeaderTitle(column) }}
          </div>
          <DxTextBox
            @keydown.stop="none"
            @click.stop="none"
            v-else
            :placeholder="column.column.caption"
            :Value="getHeaderTitle(column)"
            @focusOut="
              (event) => setHeader(event, column.column, column.columnIndex)
            "
            @enterKey="
              (event) => setHeader(event, column.column, column.columnIndex)
            "
          />
        </div>
      </template>
    </DataGrid>
    <Pagination
      v-model:page="pageInfo"
      @update:page="setPageToUtl"
    ></Pagination>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import ImageUpload from "@/components/image-upload.vue";
import { ApiTool } from "@/api/api-tool";
import { Inject, Watch } from "vue-property-decorator";
import {
  OutPutDrugInfo,
  OutputSpecificationSimpleModel,
} from "@/api/api_dictionaryclient";
import notify from "devextreme/ui/notify";
import { DxHtmlEditor } from "devextreme-vue/html-editor";
import Pagination from "@/framework/elementui/pagination.vue";
import DxTabs from "devextreme-vue/tabs";

import {
  DxDataGrid,
  DxColumn,
  DxPaging,
  DxEditing,
  DxLookup,
  DxForm,
  DxSearchPanel,
  DxExport,
  DxSorting,
  DxPager,
  DxRequiredRule,
  DxEmailRule,
  DxPatternRule,
  DxAsyncRule,
  DxSelection,
} from "devextreme-vue/data-grid";
import DataGrid from "@/framework/components/data-grid/data-grid.vue";
import { DxPopup } from "devextreme-vue/popup";
import DxButton from "devextreme-vue/button";
import { SearchByURL } from "@/utils/search-byurl";
import { PageInfo, Tool } from "@/utils/tool";
import DxTextBox from "devextreme-vue/text-box";
import { DictionaryFieldOutput } from "@/api/api_solutionclient";
import { CatalogClient } from "@/api/api_catalogclient";
import { ViewTool } from "@/framework/utils/view-tool";
import DxSortable from "devextreme-vue/sortable";
import Tree from "@/framework/components/tree/tree.vue";
import { RightContextI } from "@/framework/components/right-menu/right-menu.vue";
// import CreateMiddle from "./create-middle.vue";
import { DrugClient } from "@/api/api_drugclient";
import DrugSkuData from "@/data-source/drug-sku";
import CreateDrug from "./create-drug.vue";
import CreateDrugAgree from "./create-drug-agree.vue";
import CreateDrugMade from "./create-drug-made.vue";
import CreateDrugStadard from "./create-drug-standard.vue";
import { dxDataGridOptions } from "devextreme/ui/data_grid";
import { SpecificationClient } from "@/api/api_specificationclient";
import CreateDrugStadardzh from "./create-drug-standardzh.vue";

const componentInfo = {
  title: "药品信息",
};
const dataSourceKey = "dictionaryId";
let formData: any = {};
let self: any;
const keyExpr = "specificationId";
// 配置类型 1：金融中心产品轮播图 2：金融产品类型配置 3：还款方式 4 协议配置
const getDataGridSetting = function () {
  return {
    height: "calc(33vh - 90px)",
    width: "calc(100vw - 355px)",
    showBorders: true,
    showColumnLines: false,
    showRowLines: false,
    hoverStateEnabled: true,
    allowColumnResizing: true,
    allowColumnReordering: true,
    remoteOperations: false,
    sorting: {
      mode: "single",
    },
    selection: {
      mode: "single",
    },
    keyExpr,
    rowAlternationEnabled: true,
    noDataText: "当前药品暂无规格，右键新增规格",
    onToolbarPreparing: (e) => {
      let toolbarItems = e.toolbarOptions.items;
      toolbarItems.length = 0;
    },
    columns: [
      {
        caption: "编码",
        dataField: "coding",
        width: 160,
        disabled: true,
      },
      {
        caption: "名称",
        dataField: "name",
        width: 160,
        disabled: true,
      },
      {
        caption: "服务对象",
        dataField: "serviceObjectName",
        width: 160,
      },
      {
        caption: "医保类型",
        dataField: "drugInsurance",
        width: 160,
      },
      {
        caption: "发药类型",
        dataField: "medicineType",
        width: 160,
      },
      {
        caption: "成本价格",
        dataField: "costPrice",
        width: 160,
      },
      {
        caption: "结算价",
        dataField: "settlementPrice",
        width: 160,
      },
      {
        caption: "住院分零",
        dataField: "beHospitalizedDivideZero",
        width: 160,
      },
      {
        caption: "门诊分零",
        dataField: "zeroOutpatient",
        width: 160,
      },
      {
        caption: "非常备药",
        dataField: "isPreparedMedical",
        width: 160,
      },
      {
        caption: "药价属性",
        dataField: "attributes",
        width: 160,
      },
      {
        caption: "指导差率%",
        dataField: "guideDifference",
        width: 160,
      },
      {
        caption: "加成率%",
        dataField: "markupRate",
        width: 160,
      },
      {
        caption: "采购扣率%",
        dataField: "purchaseDeductionRate",
        width: 160,
      },
      {
        caption: "当前售价",
        dataField: "currentSellingPrice",
        width: 160,
      },
      {
        caption: "管理费比例%",
        dataField: "managementFeeRatio",
        width: 160,
      },
      {
        caption: "费别折扣",
        dataField: "feeDiscount",
        width: 160,
      },
      {
        caption: "增值税率%",
        dataField: "vatRate",
        width: 160,
      },
      {
        caption: "指导售价",
        dataField: "guidePrice",
        width: 160,
      },
      {
        caption: "收入项目",
        dataField: "incomeItem",
        width: 160,
      },
      {
        caption: "药价级别",
        dataField: "drugPriceLevel",
        width: 160,
      },
      {
        caption: "病案费目",
        dataField: "medicalRecordCost", //
        width: 160,
      },
      {
        caption: "申领单位",
        dataField: "claimUnit",
        width: 160,
      },
    ],
    editing: {
      allowAdding: false,
      allowDeleting: false,
      allowUpdating: false,
      mode: "popup",
    },
    export: {
      enabled: true,
      allowExportSelectedData: true,
      fileName: componentInfo.title + new Date(),
    },
    onEditingStart(item) {
      formData = item.data;
    },
  } as dxDataGridOptions;
};

@Options({
  components: {
    DxDataGrid,
    DxColumn,
    DxPaging,
    DxEditing,
    DxPopup,
    DxLookup,
    DxForm,
    DxSearchPanel,
    DxExport,
    DxSorting,
    DxPager,
    DxRequiredRule,
    DxEmailRule,
    DxPatternRule,
    DxAsyncRule,
    DxSelection,
    ImageUpload,
    DxHtmlEditor,
    Pagination,
    DxTextBox,
    DxButton,
    DxSortable,
    Tree,
    DxTabs,
    CreateDrug,
    CreateDrugStadard,
    DataGrid,
    CreateDrugStadardzh,
    CreateDrugAgree,
    CreateDrugMade,
  },
})
export default class GrugSku extends Vue {
  @Inject()
  apiTool: ApiTool;
  importFile: any = {};
  formData: any = {
    page: {
      pageSize: 10,
    },
  };
  listData: DrugSkuData;
  items: OutputSpecificationSimpleModel[] = [];
  // 目录id
  get drugSortId() {
    return (this.$route.query.drugSortId || "") as string;
  }
  // 方案id
  get drugSchemeId() {
    return (this.$route.query.drugSchemeId || "") as string;
  }
  // 父目录id
  get parentId() {
    return (this.$route.query.parentId || "") as string;
  }
  // 药品id
  get drugId() {
    return (this.$route.query.drugId || "") as string;
  }
  // 药品id
  get specificationId() {
    return (this.$route.query.specificationId || "") as string;
  }

  // 药品类型
  get drugType(): number {
    return Tool.convertToNumber(this.$route.query.drugType as string, 0);
  }

  pageInfo: PageInfo = {
    count: 0,
    pageSize: 10,
    index: 0,
  };
  searchByURL: SearchByURL;
  openTab = 0;
  isImport = false;
  solutionId = "";
  catalogId = "";
  catalogName = "";
  displayId = "";
  isEditHeader: Array<boolean> = [];
  headerNameList: Map<string, DictionaryFieldOutput> = new Map();

  // 西成药规格弹窗
  isCreateDrug = false;
  // 中草药规格弹窗
  isCreateDrugSkuZc = false;
  // 协定药品弹窗
  isCreateDrugAgree = false;
  // 自制药品弹窗
  isCreateDrugMade = false;

  @Inject()
  rightContextOption: RightContextI;
  rightMenu = [
    {
      text: "新增",
      id: "add",
    },
    {
      id: "edit",
      text: "修改",
    },
    {
      id: "remove",
      text: "删除",
    },
    {
      id: "setting",
      text: "设置",
      items: [
        {
          id: "groupDrug",
          text: "协定药品",
        },
        {
          id: "madeByMyself",
          text: "自制药品",
        },
      ],
    },
    {
      id: "import",
      text: "导入",
    },
    {
      id: "enable",
      text: "启用",
    },
    {
      id: "disable",
      text: "禁用",
    },
    {
      text: "显示",
      id: "show",
      items: [
        {
          id: "showAbled",
          text: "启用",
          isCheckBox: true,
          value: true,
        },
        {
          id: "showDisabled",
          text: "停用",
          isCheckBox: true,
          value: false,
        },
      ],
    },
  ];
  columns = [
    {
      caption: "中标价格",
      dataField: "biddingPrice",
      width: 160,
    },
    {
      caption: "差价让利",
      dataField: "priceDifference",
      width: 160,
    },
    {
      caption: "基药类型",
      dataField: "typeOfBaseDrug",
      width: 160,
    },
  ];
  columnsZh = [
    {
      caption: "采购限价",
      dataField: "purchaseLimit",
      width: 160,
    },
    {
      caption: "规格形态",
      dataField: "drugSpecificationSpecificationAndForm",
      width: 160,
    },
  ];

  @Watch("drugType")
  getDrugType() {
    this.setAllClick()
  }
  @Watch("$route.query.drugId")
  watchQuery(newVal) {
    this.pageInfo.index = 0;
    this.pageInfo.count = 0;
    this.getList();
  }
  
  setAllClick() {
    this.DataGridSetting.columns = Object.assign([],this.columnsDefault);
    if (this.drugType == 1) {
      this.columns.forEach((element) => {
        this.DataGridSetting.columns.push(element);
      });}
    else if (this.drugType == 2) {
      this.columns.forEach((element) => {
        this.DataGridSetting.columns.push(element);
      });
    } else if (this.drugType == 3) {
      this.columnsZh.forEach((element) => {
        this.DataGridSetting.columns.push(element);
      });
    }
  }
  DataGridSetting = getDataGridSetting.call(this);
  columnsDefault = this.DataGridSetting.columns;
 

  async getDrugs() {
    let client = this.apiTool.createClient(DrugClient);
    return await client.getList(this.formData);
  }
  // 获取第一项数据
  getFirstItem(list: any[]) {
    return list[0];
  }

  // 选中的项
  selectedRowKeys = [];
  selectItem(e: { selectedRowKeys: string[] }) {
    let specificationId = e.selectedRowKeys[0];
    this.searchByURL.setParamsToUrl({ specificationId });
  }

  // // 拖动结束
  // onDragEnd(e) {
  //   // 无效拖动
  //   if (e.toData == "listData") {
  //     return;
  //   }
  //   let dataKey = "item";
  //   let fromIndex = e.itemElement.rowIndex;
  //   let toIndex = e.toIndex;
  //   let items = this.items;
  //   let fromItem = items[fromIndex];
  //   let treeNodes = LoadElement.selectElementAll(".tree-node-item");
  //   let toItem = JSON.parse(treeNodes[toIndex].dataset[dataKey]);
  //   let { catalogId } = toItem;
  //   // 无效拖动
  //   if (catalogId == fromItem.catalogId) {
  //     return;
  //   }
  //   let editItem = Object.assign(fromItem, { catalogId });
  //   // let client = this.apiTool.createClient(DictionaryClient);
  //   // this.editItem(editItem, client);
  // }
  setRightMenu(e) {
    this.rightContextOption.content = {
      event: e,
      id: "drugSku",
    };
    // 是否可修改
    let row = e.row;
    this.rightMenu[1]["disabled"] = !row;
    this.rightMenu[2]["disabled"] = !row;
    this.rightMenu[3]["disabled"] = !row;
    this.rightContextOption.items = this.rightMenu;
  }
  isAttr = false;
  eye() {
    this.isAttr = true;
  }

  editSpecificationId = ""; // 编辑规格id
  rightClick(event: CustomEvent) {
    let { detail = {} } = event;
    let { itemData, content } = detail;
    if (content.id != "drugSku") {
      return;
    }

    let row: any;
    switch (itemData.id) {
      // 添加
      case "add":
        this.editSpecificationId = "";
        switch (this.drugType) {
          case 1: // 西成药显示
          case 2: // 中成药
            this.isCreateDrug = true;
            break;
          case 3: // 中草药显示
            this.isCreateDrugSkuZc = true;
            break;
          default:
            break;
        }
        break;

      // 编辑
      case "edit":
        row = content.event.row;
        if (row && row.key) {
          this.editSpecificationId = row.key;
          switch (this.drugType) {
            case 1: // 西成药显示
            case 2: // 中成药
              this.isCreateDrug = true;
              break;
            case 3: // 中草药显示
              this.isCreateDrugSkuZc = true;
              break;
            default:
              break;
          }
        }
        break;

      // 删除
      case "remove":
        row = content.event.row;
        this.listData.delete(row.key).then((isDelete) => {
          if (isDelete) {
            this.getList();
          }
        });
        break;

      // 协定药品
      case "groupDrug":
        row = content.event.row;
        this.editSpecificationId = row.key;
        this.isCreateDrugAgree = true;
        break;

      // 自制药品
      case "madeByMyself":
        row = content.event.row;
        this.editSpecificationId = row.key;
        this.isCreateDrugMade = true;
        break;
      default:
        break;
    }
  }
  beforeUnmount() {
    document.removeEventListener("rightContext", this.rightClick);
    
  }
  async mounted() {
    document.addEventListener("rightContext", this.rightClick);
    this.searchByURL = new SearchByURL(this.$router, 0);
    let client = this.apiTool.createClient(SpecificationClient);
    this.listData = new DrugSkuData(client, this);
    this.getList();
    this.setAllClick()
    
  }
  addSuccess() {
    this.getList();
  }
  async getList() {
    if (!this.drugId) {
      this.items = [];
      return;
    }
    let result = await this.listData.getList({
      pageInfo: this.pageInfo,
      drugId: this.drugId,
    });
    this.items = result.data;
    let selectedRowKey = this.getSelectKey(this.items, this.specificationId);
    if (selectedRowKey) {
      this.selectedRowKeys = [selectedRowKey];
    }
    this.pageInfo.count = result.dataCount;
  }

  // 获取选中id
  getSelectKey(list: OutputSpecificationSimpleModel[], id: string): string {
    let ids = list.map((item) => item.specificationId);
    if (ids.length == 0) {
      return;
    }
    if (ids.includes(id)) {
      return id;
    } else {
      this.searchByURL.setParamsToUrl({
        specificationId: ids[0],
      });
      return ids[0];
    }
  }

  setPageToUtl() {
    this.searchByURL.setParamsToUrl({ page: this.pageInfo.index });
  }
  
  // 获取表格标题
  getHeaderTitle(column, headerNameList = this.headerNameList): string {
    let dataField = column.column.dataField.replace("v", "V");
    let caption = column.column.caption;
    let title = headerNameList.get(dataField);
    return title ? title.name : caption;
  }
  // 获取上传文件
  getFile(file) {
    this.importFile = file;
  }
  // 
  uploadXlsx() {
    let client = this.apiTool.createClient(CatalogClient);
    let catalogId = this.catalogId;
    let solutionId = this.solutionId;
    let tempFileInfo = this.importFile[0];
    if (!catalogId) {
      notify("请选择需要导入数据的目录");
      return;
    }
    ViewTool.showLoading(true, this);
    client
      .importCatalog({
        catalogId,
        solutionId,
        tempFileInfo,
      })
      .then((result) => {
        if (result.isSuccess) {
          notify("导入完成", "success", 2000);
          setTimeout(() => {
            this.refresh();
          }, 1000);
        } else {
          notify(result.message, "error", 2000);
        }
        ViewTool.showLoading(false, this);
      })
      .catch((e) => {
        notify("系统异常", "error", 2000);
        ViewTool.showLoading(false, this);
      });
  }
  // 页面刷新
  refresh() {
    this.$router.replace({ path: "/refresh" });
  }
}
</script>

<style scoped lang="scss">
.grup-body {
  display: flex;
  justify-content: space-evenly;
}
.header-input {
  input {
    padding: 0 !important;
  }
}
</style>
